package com.yejing.httpdemo;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class RestUtil {
 
    /**
     * GET请求，获取JSONObject信息
     * @param url
     * @return JSONObject
     * @throws Exception
     */
    public static JSONObject getByHttps(String url) throws Exception {
        CloseableHttpClient httpclient = getSSLClient();
        try {
            HttpGet httpget = new HttpGet(url); // 创建httpget.
            CloseableHttpResponse response = httpclient.execute(httpget); // 执行get请求.
            try {
                return covertEntityToJSON(response.getEntity()); // 获取响应实体
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
    public static JSONObject getByHttp(String url) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                return covertEntityToJSON(response.getEntity());
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
    public static String getStringByHttps(String url) throws Exception {
        CloseableHttpClient httpclient = getSSLClient();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String res = EntityUtils.toString(entity, "UTF-8");
                    return res;
                } else {
                    return null;
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
    public static String getStringByHttps(String url, String cookie) throws Exception {
        CloseableHttpClient httpclient = getSSLClient();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            httpget.addHeader("Cookie", cookie);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String res = EntityUtils.toString(entity, "UTF-8");
                    return res;
                } else {
                    return null;
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
    /**
     * GET请求，获取byte数组信息
     *
     * @param url
     * @return byte[]
     * @throws Exception
     */
    public static byte[] getBinaryByHttps(String url) throws Exception {
        CloseableHttpClient httpclient = getSSLClient();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                return covertEntityToBinary(response.getEntity());
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
    /**
     * POST请求 HTTP
     *
     * @param url
     * @param parameters
     * @return
     * @throws Exception
     */
    public static JSONObject postHttp(String url, String parameters) throws Exception {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = getSSLClient();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        StringEntity s = new StringEntity(parameters.toString());
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");//发送json数据需要设置contentType
        httpPost.setEntity(s);
        HttpResponse res = httpclient.execute(httpPost);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            String result = EntityUtils.toString(res.getEntity(), "UTF-8");// 返回json格式：
            JSONObject jsonObject = JSONObject.parseObject(result);
            return jsonObject;
        }
        return null;
    }
 
    public static String postHttpForm(String url, JSONObject parameters, String cookie) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Cookie", cookie);
        // 创建参数队列
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        Set<String> keySet = parameters.keySet();
        for (String key : keySet) {
            String value = parameters.get(key).toString();
            if (value.equals("null") != true) {
                nameValuePairs.add(new BasicNameValuePair(key, value));
            }
        }
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
            httpPost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                String res = EntityUtils.toString(response.getEntity(), "UTF-8");
                return res;
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    private static SSLConnectionSocketFactory getSslConnectionSocketFactory()
            throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    }

    public static CloseableHttpClient getSSLClient() throws Exception {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient httpClient = httpClientBuilder//
                .setSSLSocketFactory(getSslConnectionSocketFactory())//
                .build();//
        return httpClient;
    }

    /**
     * POST请求 HTTPS
     *
     * @param url
     * @param parameters
     * @return JSONObject
     * @throws Exception
     */
    public static JSONObject postHttps(String url, JSONObject parameters) throws Exception {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpClient = getSSLClient();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        Set<String> keySet = parameters.keySet();
        for (String key : keySet) {
            String value = parameters.get(key).toString();
            if (value.equals("null") != true) {
                nameValuePairs.add(new BasicNameValuePair(key, value));
            }
        }
        return executeSendRequest(httpClient,httpPost,nameValuePairs);
    }
 
    /**
     * 执行发送请求
     * @param httpclient
     * @param httpPost
     * @param nameValuePairs
     * @return JSONObject
     * @throws Exception
     */
    private static JSONObject executeSendRequest(CloseableHttpClient httpclient,
                                                 HttpPost httpPost,
                                                 List<NameValuePair> nameValuePairs) throws Exception {
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
            httpPost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                return covertEntityToJSON(response.getEntity());
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
    /**
     * 将HttpEntity转换成JSONObject
     *
     * @param entity
     * @return JSONObject
     * @throws Exception
     */
    private static JSONObject covertEntityToJSON(HttpEntity entity) throws Exception {
        if (entity != null) {
            String res = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(res);
            return jsonObject;
        } else {
            return null;
        }
    }
 
    /**
     * 将HttpEntity转换成byte[]
     *
     * @param entity
     * @return byte[]
     * @throws Exception
     */
    private static byte[] covertEntityToBinary(HttpEntity entity) throws Exception {
        if (entity != null) {
            byte[] res = EntityUtils.toByteArray(entity);
            return res;
        } else {
            return null;
        }
    }
 
    public static void main(String[] args) throws Exception {




    }
}